var EventProxy = require('eventproxy');

var logger = require('../models/logger');
var resultJson = require('../result-json');
var arrayHelper = require('./arrayHelper');

var weightHelper = {
	updateWeight(Table, items, weight, item, _id, cb) {
		logger.debug('come to updateWeight');
		logger.debug(' items, weight, item, _id', items, weight, item, _id);
		var ids = [];
		var weights = [];
		items.map(function(item) {
			weights.push(item.weight);
		});
		var min = 0
		if (weights.length != 0) {
			min = weightHelper.getMinWeight(weights);
		}
		logger.debug('min', min);
		if (weight < min) {
			cb(0);
		} 
		if (!_id && weight >= min) {
			items.map(function(item) {
				if (item.weight >= weight) {
					ids.push(item._id);
				}
			});
		}
		if (_id && weight >= min ) {
			items.map(function(item) {
				if (item.weight >= weight && item._id != _id) {
					ids.push(item._id);
				}
			});
		}
		var setobj = {}
		logger.debug('item', item);
		logger.debug('ids',ids);
		if (item) {
			setobj = item;
		} else {
			setobj = {
				$inc: {
					weight: 1
				}
			}
		}
		logger.debug(ids);
		if (ids.length != 0) {
			Table.update({
				_id: {
					$in: ids
				}
			}, setobj, {
				safe: true,
				multi: true
			}, function(err) {
				if (err) {
					logger.error(err);
					cb(2);
				}
				cb(0);
			});
		} else {
			cb(0);
		}

	},
	getMinWeight(weights) {
		let min = weights[0]; 
		for (let i = 0; i < weights.length; i ++) {
			if (weights[i] < min) {
				min = weights[i];
			}
		}
		return min;
	}
}




module.exports = weightHelper;